package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @ClassName $ {NAME}
 * @Description TODO
 * @Author 寇铭
 * @Date 2022/6/13 11:18
 * @Version 1.0
 **/
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增菜品，同时保存对应的口味数据
     *
     * @param dishDto 将菜品和口味合并为一个对象，分别将菜品的数据和口味的数据存入响应的表
     */
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {

        String dishDtoName = dishDto.getName();
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getName, dishDtoName);
        Dish dish = this.getOne(queryWrapper);
        //如果添加的菜品是已经被删除过的，只需要把isDelete改为0
        if (dish != null && dish.getIsDeleted() == 1) {
            dish.setIsDeleted(0);
            this.updateById(dish);
        }else {
            //保存菜品的基本信息到菜品表dish
            this.save(dishDto);
            Long dishId = dishDto.getId();//菜品id
            //菜品口味
            List<DishFlavor> flavors = dishDto.getFlavors();
            flavors = flavors.stream().map((item) -> {
                item.setDishId(dishId);
                return item;
            }).collect(Collectors.toList());

            //保存菜品口味数据到菜品口味表dish_flavor
            dishFlavorService.saveBatch(flavors);
        }

    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {

        //查询菜品基本信息，从dish表查询
        Dish dish = this.getById(id);

        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);

        //查询当前菜品对应的口味信息。从dish_flavor表查询
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(flavors);
        return dishDto;
    }

    @Override
    public void updateWithFlavor(DishDto dishDto) {
        //更新dish表基本信息
        this.updateById(dishDto);

        //清理当前菜品对应口味数据---dish_flavor表的delete操作
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dishDto.getId());

        dishFlavorService.remove(queryWrapper);

        //添加当前提交过来的口味数据---dish_flavor表的insert操作
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);

    }

    @Override
    public void deleteByIds(Long[] ids) {
        //将ids数组转为list集合
        List<Long> dishIds = new ArrayList<>();
        for (Long id : ids) {
            dishIds.add(id);
        }

        //遍历dishids集合中的每一个id，通过该id查询当前菜品状态，如果起售则不能删除抛出异常，如果停售则删除该菜品和口味表中的相关数据
        for (Long dishId : dishIds) {
            LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Dish::getId, dishId);
            Dish dish = this.getOne(queryWrapper);
            if (dish.getStatus() == 1) {
                throw new CustomException(dish.getName() + "启售中，不能删除");
            } else {
                this.removeById(dishId);
                LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(DishFlavor::getDishId, dishId);
                dishFlavorService.remove(wrapper);
            }

        }

    }

    @Override
    public void updateStatusByIds(int status, Long[] ids) {
        //将ids数组转为list集合
        List<Long> dishIds = new ArrayList<>();
        for (Long id : ids) {
            dishIds.add(id);
        }


        //遍历dishids集合中的每一个id，通过该id查询套餐菜品表，如果当前有套餐关联此菜品，不能修改状态
        for (Long dishId : dishIds) {
            LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SetmealDish::getDishId, dishId);
            List<SetmealDish> setmealDishList = setmealDishService.list(queryWrapper);

            if (setmealDishList.size() > 0) {
                throw new CustomException("当前菜品与套餐关联不能禁售");
            }

            Dish dish = this.getById(dishId);
            //注意，接收到的参数status是要把菜品改为什么状态，不是菜品的当前状态
            if (status == 1) {
                dish.setStatus(1);
            } else {
                dish.setStatus(0);
            }
            this.updateById(dish);

        }
    }

}

























